package com.example.codediff.service;

import com.example.codediff.model.CompareResult;
import lombok.Data;
import org.springframework.stereotype.Component;

import java.nio.file.Path;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 比对结果缓存
 * 用于存储比对结果和临时文件路径
 */
@Component
public class CompareResultCache {
    
    @Data
    public static class CacheEntry {
        private final CompareResult compareResult;
        private final Path newJarPath;
        private final long timestamp;
        
        public CacheEntry(CompareResult compareResult, Path newJarPath) {
            this.compareResult = compareResult;
            this.newJarPath = newJarPath;
            this.timestamp = System.currentTimeMillis();
        }
    }
    
    private final Map<String, CacheEntry> cache = new ConcurrentHashMap<>();
    
    /**
     * 生成缓存key
     */
    public String generateKey(String oldJarName, String newJarName, String packagePrefix) {
        return String.format("%s_%s_%s", oldJarName, newJarName, packagePrefix);
    }
    
    /**
     * 保存比对结果
     */
    public void put(String key, CompareResult result, Path newJarPath) {
        cache.put(key, new CacheEntry(result, newJarPath));
    }
    
    /**
     * 获取比对结果
     */
    public CacheEntry get(String key) {
        return cache.get(key);
    }
    
    /**
     * 清理过期的缓存项（1小时过期）
     */
    public void cleanup() {
        long now = System.currentTimeMillis();
        long oneHour = 60 * 60 * 1000;
        
        cache.entrySet().removeIf(entry -> 
            (now - entry.getValue().getTimestamp()) > oneHour);
    }
}
